using System;
using System.IO;

namespace SoftwareMonkeys.Scriptech.Projects
{
	public class ProjectSlnConverter
	{
		public string StoreName = String.Empty;
		public string GroupName = String.Empty;
		public string ProjectName = String.Empty;
		
		public Project Convert()
		{
			string projectPath = ProjectFileNamer.GetProjectPath(StoreName, GroupName, ProjectName);
			
			string slnFilePath = String.Empty;
			
			foreach (string file in Directory.GetFiles(projectPath, "*.sln", SearchOption.AllDirectories))
			{
				slnFilePath = file;
			}
			
			return ConvertFromFile(slnFilePath);
		}
		
		public Project ConvertFromFile(string slnFilePath)
		{
			string content = String.Empty;
			
			using (StreamReader reader = new StreamReader(File.OpenRead(slnFilePath)))
			{
				content = reader.ReadToEnd();
			}
			
			return ConvertFromContent(slnFilePath, content);
		}
		
		public Project ConvertFromContent(string slnFilePath, string slnContent)
		{
			string fileName = Path.GetFileName(slnFilePath);
			
			Project project = new Project();
			project.Name = fileName.Substring(0, fileName.IndexOf("."));
			
			project.AssembliesDirectory = ExtractAssembliesDirectory(slnFilePath, project);
			
			return project;
		}
		
		public string ExtractAssembliesDirectory(string slnFilePath, Project project)
		{
			string dir = Path.GetDirectoryName(slnFilePath);
			
			string projectPath = ProjectFileNamer.GetProjectPath(StoreName, GroupName, ProjectName);
			
			dir = dir.Replace(projectPath, "");
			dir = dir.Trim(Path.DirectorySeparatorChar);
			
			return dir;
		}
	}
}

